const { Op, Sequelize } = require("sequelize");
const ArticleLiked = require('../model/article_liked.model');
const seq = require('../db/seq')
class LikedService {

    // 点赞
    async saveLikedService(param) {
        const { id = 0, article_id, author, authoruser_id, operateuser, title, operateuser_id } = param
        const where = {
            article_id: { [Op.eq]: article_id },
            operateuser_id: { [Op.eq]: operateuser_id }
        }
        const res = await ArticleLiked.findOne({
            where
        })
        if (!res) {
            const data = await ArticleLiked.create({ id: id, article_id: article_id, author: author, authoruser_id: authoruser_id, operateuser: operateuser, title: title, operateuser_id: operateuser_id })
            return 'success'
        } else {
            return 'have'

        }
    }

    // 获得单篇文章的点赞量
    async getOneArticleLikedService(param) {
        const { article_id, operateuser_id } = param;

        // 用到了 SUM 和 literal
        try {
            let result;
            //这篇文章的获赞量
            await seq.query(`SELECT COUNT(article_id) AS count FROM ArticleLikeds WHERE article_id=${article_id}`, { type: seq.QueryTypes.SELECT }).then((res) => {
                //  return 不能写到promise中
                console.log(res)
                result = res
            })
            // 阅读的人是否点赞了这个文章
            await seq.query(`SELECT COUNT(id) AS count FROM ArticleLikeds WHERE operateuser_id=${operateuser_id} AND article_id=${article_id} `, { type: seq.QueryTypes.SELECT }).then((res) => {
                console.log(res[0].count, '🐅')
                res[0].count > 0 ? result[0]['liked'] = true : result[0]['liked'] = false
            })
            console.log(result)
            return result

        } catch (err) {
            return err
        }
    }
    // 获得单篇文章的点赞量
    async getAllArticleLikedService(param) {
        const { user_id } = param;

        // 用到了 SUM 和 literal
        try {
            let result;
            //这篇文章的获赞量
            await seq.query(`SELECT COUNT(article_id) AS count FROM ArticleLikeds WHERE authoruser_id=${user_id}`, { type: seq.QueryTypes.SELECT }).then((res) => {
                //  return 不能写到promise中
                console.log(res)
                result = res
            })
            return result

        } catch (err) {
            return err
        }
    }
}
// 导出后 在控制器controller中使用
module.exports = new LikedService()